<template>
	<view class="layout">
		<wd-form ref="form" :model="model">
			<wd-cell-group border>
				<wd-input label="分类名" label-width="100px" prop="name" clearable v-model="model.name"
						  placeholder="请输入分类名" :rules="[{ required: true, message: '请填写分类名' }]"/>
			</wd-cell-group>
			<view class="footer">
				<wd-button type="primary" size="large" @click="handleSubmit" block :loading="loading"
						   :disabled="loading">提交
				</wd-button>
			</view>
		</wd-form>
	</view>

	<wd-notify/>
</template>

<script setup>
import {reactive, ref} from 'vue';
import typeApi from '../../apis/type';
import {useNotify} from 'wot-design-uni';

// 消息通知组件
const {showNotify} = useNotify();

const model = reactive({
	name: '',
});

const form = ref();

// 加载状态，默认为false
const loading = ref(false);

const handleSubmit = async () => {
	loading.value = true;
	form.value
		// 验证数据格式
		.validate()
		.then(async ({valid}) => {
			// 如果验证通过
			if (valid) {
				await typeApi.addType(model).then((result) => {
					console.log(result)
					showNotify({
						message: result.msg,
						type: 'success',
						duration: 1500,
						onClosed() {
							// 跳转到首页
							uni.navigateTo({
								url: '/pages/type/index'
							})
						}
					});
				});
			}
		})
		// 验证失败时打印日志
		.catch((errors) => {
			console.log(errors, 'error');
		})
		// 最终执行
		.finally(() => {
			loading.value = false;
		})
}
</script>

<style scoped lang="scss">
.footer {
	padding: 12px;
}
</style>
